import axios from 'axios'
import {baseURL} from '@/config'
import {Message} from 'element-ui'
//创建实列
const service= axios.create({
  baseURL,
  timeout:20000
})

//添加请求拦截器
service.interceptors.request.use(config=>{
  const token=localStorage.getItem('token')
  //添加请求头
  if (token) {
    config.headers['X-token']=token
  }
  return config
},error=>{
  return Promise.reject(error)
})

//添加响应拦截器
service.interceptors.response.use(response=>{
  //获取数据
  const res=response.data
  if (res.code !==10000) {
    Message.error(res.message)
  }
  //登陆超时
  if (res.code===-2) {
    //清除token 跳转登陆页
    localStorage.removeItem('token')
    window.location.href=location.origin+'/cms-manage/#/login'
  }
  return res
},err=>{
  console.log(err);
  return Promise.reject(err)
})

export default service